import { Inject, Injectable } from '@nestjs/common';
import puppeteer from 'puppeteer';
import { PrismaService } from 'src/prisma/prisma.service';
import { WorkInfo } from './dto/create-boss.dto';
import { cityData } from './city';

@Injectable()
export class BossService {
  @Inject()
  private readonly prisma: PrismaService;

  findCityByName(cities, cityName) {
    // 遍历省份
    for (const province of cities) {
      // 遍历省份下的城市
      if (province.subLevelModelList) {
        for (const city of province.subLevelModelList) {
          if (city.name === cityName) {
            return city;
          }
        }
      }
    }
    // 如果没有找到匹配的城市
    return null;
  }

  // 爬虫函数
  async startSpider(info: WorkInfo) {
    const { city, job } = info;
    const cityCode = this.findCityByName(cityData, city);
    const browser = await puppeteer.launch({
      headless: false,
      defaultViewport: {
        width: 0,
        height: 0,
      },
      args: ['--no-sandbox', '--disable-setuid-sandbox'],
    });

    const page = await browser.newPage();

    await page.goto(
      'https://www.zhipin.com/web/geek/job?query=前端&city=100010000',
    );

    await page.waitForSelector('.job-list-box');

    const totalPage = await page.$eval(
      '.options-pages a:nth-last-child(2)',
      (e) => {
        return parseInt(e.textContent);
      },
    );

    const allJobs = [];
    for (let i = 1; i <= totalPage; i++) {
      await page.goto(
        `https://www.zhipin.com/web/geek/job?query=${job}&city=${cityCode.code}&page=` +
          i,
      );

      await page.waitForSelector('.job-list-box');

      const jobs = await page.$eval('.job-list-box', (el) => {
        return [...el.querySelectorAll('.job-card-wrapper')].map((item) => {
          return {
            city: item.querySelector('.job-area').textContent,
            name: item.querySelector('.job-name').textContent,
            area: item.querySelector('.job-area').textContent,
            salary: item.querySelector('.salary').textContent,
            years: item.querySelector('.tag-list').children[0].textContent,
            education: item.querySelector('.tag-list').children[1].textContent,
            link: item.querySelector('a').href,
            companyName: item.querySelector('.company-name').textContent,
          };
        });
      });
      allJobs.push(...jobs);

      // 添加延迟
      await new Promise((resolve) => setTimeout(resolve, 100));
    }

    for (let i = 0; i < allJobs.length; i++) {
      await page.goto(allJobs[i].link);

      try {
        await page.waitForSelector('.job-sec-text');

        const jd = await page.$eval('.job-sec-text', (el) => {
          return el.textContent;
        });
        allJobs[i].JobDetails = jd;

        console.log(allJobs[i]);
      } catch (e) {}
    }

    return allJobs;
  }
  // 主函数
  async main(workInfo) {
    const res = await this.startSpider(workInfo);
    return this.prisma.bossWorkList.createMany({
      data: res,
    });
  }

  // 查询函数
  async findAll() {
    return this.prisma.bossWorkList.findMany();
  }
}
